<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- bootstrap -->
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <div class="container p-5 col-sm-8 col-md-4 shadow mt-3 rounded border boeder-3">
      <h2 class="align-item-center mt-5 mb-3">欢迎-登陆</h2>
      <!-- 提示 -->
      <div class="alert alert-success fade" role="alert">提示信息:xxxxxxx</div>
      <form class="form" action="">
        <label class="form-label mt-1 fs-6 lh-lg" for="">用户名</label>
        <input class="form-control border border-3 username" type="text" />
        <label class="form-label mt-4 fs-6 lh-lg" for="">密码</label>
        <input class="form-control border border-3 password" type="password" />
        <button class="btn btn-primary btn-login mt-3 mb-5" type="button">登陆</button>
      </form>
    </div>
    <!-- js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
    <script>
      // 接口和信息
      // url: 'http://hmajax.itheima.net/api/login'
      // '我叫阿卜杜合力力'  '2062454635'

      // 提示框
      const myAlert = document.querySelector('.alert');
      function alertFn(msg, isSuccess) {
        // 显示
        myAlert.classList.add('show');

        // 文字
        myAlert.innerHTML = msg;
        const bgStyle = isSuccess ? 'bg-success' : 'bg-danger';
        myAlert.classList.add(bgStyle);

        // 消失
        setTimeout(() => {
          myAlert.classList.remove('show');
          myAlert.classList.remove(bgStyle); // 避免类名冲突
        }, 2000);
      }

      // 点击事件
      document.querySelector('button').addEventListener('click', () => {
        const username = document.querySelector('.username').value;
        const password = document.querySelector('.password').value;
        console.log(username, password);

        // 用户名最少8位
        if (username.length < 8) {
          alertFn('用户名长度不能小于8位', false);
          return;
        }
        // 密码最少6位
        if (password.length < 6) {
          alertFn('密码长度不能小于6位', false);
          return;
        }

        // 请求
        axios({
          url: 'http://hmajax.itheima.net/api/login',
          method: 'post',
          data: {
            username,
            password,
          },
        })
          .then((res) => {
            // 请求成功
            alertFn(res.data.message, true);
            console.log(res.data.message);
          })
          .catch((err) => {
            // 请求失败
            alertFn(err.response.data.message, false);
            console.log(err.response.data.message);
          });
      });
    </script>
  </body>
</html>
